package com.hujing.springsource.a17;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectInstanceFactory;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.aspectj.AspectJMethodBeforeAdvice;
import org.springframework.aop.aspectj.SingletonAspectInstanceFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 将高级的切面转换成低级的切面Advisor
 */
public class A17_2 {
    
    static class Aspect{
        @Before("execution(* foo())")
        public void before(){}
        
        @After("execution(* foo())")
        public void after(){}
    }

    public static void main(String[] args) {
        AspectInstanceFactory instanceFactory = new SingletonAspectInstanceFactory(new Aspect());

        List<Advisor> list = new ArrayList<>();
        Method[] methods = Aspect.class.getDeclaredMethods();
        for (Method method : methods) {
            // 判断method上是否有@Before注解
            if (method.isAnnotationPresent(Before.class)){
                // 创建切点
                String expression = method.getAnnotation(Before.class).value();
                AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
                pointcut.setExpression(expression);
                
                // 创建通知
                AspectJMethodBeforeAdvice advice = new AspectJMethodBeforeAdvice(method, pointcut, instanceFactory);
                
                // 创建Advisor
                DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
                list.add(advisor);
            }
        }
        
        // 打印出所有的Advisor
        for (Advisor advisor : list) {
            System.out.println(advisor);
        }
    }
}
